#ifndef TRANSFORMERCONTENTTIMER_HPP_3
#define TRANSFORMERCONTENTTIMER_HPP_3
#include <list>
#include <unistd.h>
#include "transContentDefine.h"
#include "transContentITimerEvent.hpp"

using namespace std;

class TransContentTimer{
	private:
		list<TransContentITimerEvent*> timer_funcs;
		int mInterval;
		int mState;
		volatile int working;
		static TransContentTimer* _instance;
	public:
		void addOnTimer(TransContentITimerEvent* tIns){
			//remove first invalidat add same instance twice
			timer_funcs.remove(tIns);
			timer_funcs.push_front(tIns);
		}
		
		void removeTimer(TransContentITimerEvent* tIns){
			timer_funcs.remove(tIns);
		}
		
		int getInterval(){
			return this->mInterval;
		}
		
		static TransContentTimer* getInstance(){
			if(_instance == NULL){
				_instance = new TransContentTimer();
				if(_instance->getState() != INS_STATE_OK)
					releaseInstance();
			}
			return _instance;
		}
		
		static void releaseInstance(){
			if(_instance != NULL){
				delete _instance;
				_instance = NULL;
			}
		}
		
		int getCallCount(){
			return timer_funcs.size();
		}
		
		void start(){
			if(working == 0){
				working = 1;
				timer();
			}
		}
		
		void stop(){
			working = 0;
		}

		int getState(){
			return mState;
		}
		
	private:
		TransContentTimer(){
			mState = INS_STATE_OK;
			mInterval = TransContentSetting::getContentTimerInterval();
			working = 0;
		}
		
		~TransContentTimer(){
			mState = INS_STATE_ERROR;			
		}
		
		void timer(){
			while(working){
				sleep(mInterval);
				for(list<TransContentITimerEvent*>::iterator caller = timer_funcs.begin(); caller != timer_funcs.end(); ++ caller){
					(*caller)->onTimer();
				}
			}
		}
};
#endif //TRANSFORMERCONTENTTIMER_HPP_3
